package com.golxen.framework.common.server.game.config;

import com.golxen.framework.common.server.game.config.GameConfigParamAnnotation;
import com.golxen.framework.common.server.game.dao.GameConfigParamDaoImpl;
import com.golxen.utils.LogUtil;
import com.golxen.utils.TimeUtils;

import java.util.Date;
import java.util.HashMap;

public class GameConfig {

	@GameConfigParamAnnotation(key = "CONFIG_VERSION", description = "配置版本", type = String.class, defaultValue = "1.0.0")
	public static String CONFIG_VERSION;

	public static void refresh() {
		LogUtil.COMMON.info("refreshing game config!");
		HashMap<String, String> allConfigs = new GameConfigParamDaoImpl().getGameConfig();
		load(GameConfig.class, allConfigs);
	}

	public static void load(Class<?> type, HashMap<String, String> allConfigs) {
		for (java.lang.reflect.Field field : type.getFields()) {
			GameConfigParamAnnotation annotation = field.getAnnotation(GameConfigParamAnnotation.class);
			if (annotation != null) {
				String configInfo = allConfigs.get(annotation.key());
				String valueString = annotation.defaultValue();

				if (configInfo != null && configInfo.length() > 0) {
					valueString = configInfo;
				}
				try {
					field.set(null, parseValue(annotation.type(), valueString));
				} catch (Exception e) {
					LogUtil.COMMON.error("{} fail to load:{},error:{}", type.getName(), valueString, e);
				}
			}
		}
	}


	public static Object parseValue(Class<?> fieldType, String value) {
		Object fieldValue = null;
		value = value.trim();

		try {
			if (fieldType == Integer.class) {
				fieldValue = Integer.parseInt(value);
			} else if (fieldType == Long.class) {
				fieldValue = Long.parseLong(value);
			} else if (fieldType == Boolean.class) {
				fieldValue = Boolean.parseBoolean(value);
			} else if (fieldType == Date.class) {
				if (value.length() > 10) {
					if (value.indexOf('-') != -1)
						fieldValue = TimeUtils.getSimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(value);
					else
						fieldValue = TimeUtils.getSimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse(value);
				} else if (value.length() == 8)
					fieldValue = TimeUtils.getSimpleDateFormat("HH:mm:ss").parse(value);
				else if (value.indexOf('-') != -1)
					fieldValue = TimeUtils.getSimpleDateFormat("yyyy-MM-dd").parse(value);
				else
					fieldValue = TimeUtils.getSimpleDateFormat("yyyy/MM/dd").parse(value);
			} else if (fieldType == Double.class) {
				fieldValue = Double.parseDouble(value);
			} else if (fieldType == Float.class) {
				fieldValue = Float.parseFloat(value);
			} else {
				fieldValue = value;
			}
			return fieldValue;
		} catch (Exception e) {
			LogUtil.COMMON.error("Exception : parseValue: ", e);
			return null;
		}
	}

}
